package com.alibaba.sdk.config.shiro;

import com.alibaba.sdk.constant.UserInfoConstant;
import com.alibaba.sdk.enums.UserTypeEnum;
import com.alibaba.sdk.model.dao.UserMapper;
import com.alibaba.sdk.model.entity.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * shiro获取用户信息的配置
 *
 * @ writer Shawn(Shawn_0217@163.com)
 * @ date & time 2021/4/27 0:50
 * @ company alibaba
 */
@Slf4j
@Component
public class ShiroRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;

    /**
     * 用户登录认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取用户的输入的账号
        String username = (String) authenticationToken.getPrincipal();
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername, username));
        if (user == null) {
            log.error("用户登录认证失败");
            throw new UnknownAccountException();
        }

        // 用户信息放在session里
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute(UserInfoConstant.USER, user);

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        return authenticationInfo;
    }

    /**
     * 用户权限配置
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        // 获取用户角色
        User user = (User) principals.getPrimaryPrincipal();
        UserTypeEnum userType = user.getUserType();
        authorizationInfo.addRole(userType.name());
        return authorizationInfo;
    }
}
